class Solution {
public:
    int minCost(vector<vector<int>> &costs) {
        int n = costs.size();
        vector<int> dp(3);
        for (int j = 0; j < 3; j++) {
            dp[j] = costs[0][j];
        }

        for (int i = 1; i < n; i++) {
            vector<int> nextDP(3);
            for (int j = 0; j < 3; j++) {
                nextDP[j] = costs[i][j] + min(dp[(j + 1) % 3], dp[(j + 2) % 3]);
            }
            dp = nextDP;
        }
        return min(dp[0], min(dp[1], dp[2]));
    }
};